<?php
/**
 * Created by PhpStorm.
 * User: hongyeah
 * Date: 2017/9/17
 * Time: 19:14
 */

namespace app\index\controller;

use think\Controller;
use think\Request;
use \think\Session;

define('INTRODUCER_OK_STATUS', 1);
define('KEY_CODE', 'code_');
define('KEY_SEND_TIME', 'send_time_');
define('KEY_CSRF', 'house_csrf');
define('LOGIN_KEY', '&*HFDjfdslj9872@@');

class Introducer extends Controller
{

    public function isLogin()
    {
        if ($this->hasLogin()) {
            format(CODE_OK);
        } else {
            format(-996);
        }
    }

    //登录
    public function login()
    {
        $request = Request::instance();
        $phone = $request->request('phone', '', 'SAFE_REPLACE,REMOVE_XSS');
        $code = $request->request('code', '', 'SAFE_REPLACE,REMOVE_XSS');

        if (isPhone($phone) && strlen($code) == 4) {
            $result = myRedis()->get(KEY_CODE . $phone);
            if (!empty($result) && $result == $code) {
                myRedis()->rm(KEY_CODE . $phone);
                myRedis()->rm(KEY_SEND_TIME . $phone);
                $introducerModel = model('Introducer');
                $introducer = $introducerModel->where('phone', $phone)->where('register_finish', 2)->where('status', INTRODUCER_OK_STATUS)->find();
                if (!empty($introducer['id'])) {
                    Session::set('id', $introducer['id']);
                    Session::set('name', $introducer['name']);
                } else {
                    format(CODE_OPT_FAIL, '账号不存在');
                }
                $loginToken = makeSkey(Session::get('id') . LOGIN_KEY);
                format(CODE_OK, '', array('sKey' => $loginToken));
            } else {
                format(CODE_OPT_FAIL, '验证码错误');
            }
        } else {
            format(CODE_PARAM_FAIL, '请填写正确信息');
        }
    }

    //登出
    public function logout()
    {
        $request = Request::instance();
        $sKey = $request->request('sKey', '', 'SAFE_REPLACE,REMOVE_XSS');

        if (Session::has('id') && !empty($sKey)) {
            if ($sKey == makeSkey(Session::get('id') . LOGIN_KEY)) {
                Session::delete('id');
                format(CODE_OK);
            }
        }
        format(CODE_OK);
    }

    public function getToken()
    {
        $request = Request::instance();
        $realIp = $request->ip();
        $key = 'token_'.$realIp;
        $result = myRedis()->get($key);
        $prefix = 'house_';
        $cacheKey = $prefix.$key;
        if (empty($result)) {
            myRedis()->inc($key);
            myRedis()->handler()->setTimeout($cacheKey, 60);
        } else if ($result < 10){
            myRedis()->inc($key);
        } else {
            format(CODE_OPT_FAIL);
        }

        $token = md5(mt_rand(0, 999999) . time() . KEY_CSRF);
        myRedis()->set($token, 1, 15*60);
        format(CODE_OK, '', $token);
    }

    //发送手机验证码
    public function sendCode()
    {
        $request = Request::instance();
        $phone = $request->request('phone');
        $csrfToken = $request->request('token');
        $csrfResult = myRedis()->get($csrfToken);

        $now = time();
        if (!empty($csrfToken) && $csrfResult == 1 && isPhone($phone)) {
            myRedis()->rm($csrfToken);
            $code = myRedis()->get(KEY_CODE . $phone);
            if ($code && strlen($code) == 4) {
                $sendTime = myRedis()->get(KEY_SEND_TIME . $phone);
                $sendTime = intval($sendTime);
                if (($now - $sendTime) > 60) {
                    $sendResult = sendPhoneCode($phone, $code);
                    if ($sendResult['code'] == 0) {
                        format(CODE_OK, '验证码已发送');
                    } else {
                        format(CODE_OPT_FAIL, '系统故障, 请稍后重试');
                    }
                } else {
                    format(CODE_OPT_FAIL, '短信正在火速送到您手机, 短时间内请勿重复操作');
                }
            } else {
                $code = mt_rand(99999, 999999);
                $code = $code % 10000;
                if (strlen($code) == 3) {
                    $code = 0 . $code;
                }
                myRedis()->set(KEY_CODE . $phone, $code, 15 * 60);
                myRedis()->set(KEY_SEND_TIME . $phone, $now, 100);
                $sendResult = sendPhoneCode($phone, $code);
                if ($sendResult['code'] == 0) {
                    format(CODE_OK, '验证码已发送');
                } else {
                    format(CODE_OPT_FAIL, '系统故障, 请稍后重试');
                }
            }
        } else {
            format(CODE_PARAM_FAIL, '输入信息有误');
        }
    }

    //注册-第一步
    public function registerStep1()
    {
        $request = Request::instance();
        $phone = $request->get('phone');
        $code = $request->get('code');

        //判断合法手机号和合法验证码
        if (isPhone($phone) && strlen($code) == 4) {

            //判断收到的验证码和发出的验证码是否正确
            $result = myRedis()->get(KEY_CODE . $phone);
            if (!empty($result) && $result == $code) {

                myRedis()->rm(KEY_CODE . $phone);
                myRedis()->rm(KEY_SEND_TIME . $phone);

                $introducerModel = model('Introducer');
                //找一下这个人是否已存在
                $introducer = $introducerModel->where('phone', $phone)->where('status', INTRODUCER_OK_STATUS)->find();
                if (!empty($introducer['id'])) {
                    //如果已经注册, 就返回账号已存在
                    if ($introducer['register_finish'] == 2) {
                        //生成登录sKey
                        format(CODE_EXIST, '账号已注册');
                    }
                    Session::set('id', $introducer['id']);
                } else {
                    //不存在就进入注册第一部
                    $data = array(
                        'phone' => $phone,
                        'status' => INTRODUCER_OK_STATUS,
                        'create_time' => time(),
                        'update_time' => time()
                    );
                    $result = $introducerModel->data($data)->save();
                    if (!empty($result)) {
                        $insertId = $introducerModel->getLastInsID();
                        Session::set('id', $insertId);
                    } else {
                        format(CODE_OPT_FAIL, '操作失败, 请稍后重试');
                    }
                }
                format(CODE_OK);
            } else {
                format(CODE_OPT_FAIL, '验证码错误');
            }
        } else {
            format(CODE_PARAM_FAIL, '填入信息有误');
        }
    }


    public function qiNiu()
    {
        header("Access-Control-Allow-Origin: *");

        $token = qiNiuToken();
        echo json_encode(array('uptoken' => $token));

    }

    //注册-第二步
    public function registerStep2()
    {
        //Session::set('id', 8);
        $request = Request::instance();
        $id = intval(Session::get('id'));
        $identify = $request->get('identify', '', 'SAFE_REPLACE,REMOVE_XSS');
        $name = $request->get('name', '', 'SAFE_REPLACE,REMOVE_XSS');
        $identifyFront = $request->get('if_pic', '', 'REMOVE_XSS');
        $identifyBack = $request->get('ib_pic', '', 'REMOVE_XSS');

        if (empty($id)) {
            format(CODE_OPT_FAIL, '请回到第一步注册');
        }
        if (empty($identify) || empty($name) || empty($identifyFront) || empty($identifyBack)) {
            format(CODE_PARAM_FAIL);
        } else {
            if (strlen($identify) != 18) {
                format(CODE_OPT_FAIL, '身份证号码有误!');
            } else {
                $introducerModel = model('Introducer');

                $introducer = $introducerModel->where('id', $id)->where('status', INTRODUCER_OK_STATUS)->find();
                //判断一下这个人有没有完成第一步
                if (empty($introducer)) {
                    format(CODE_OPT_FAIL, '请回到第一步注册');
                }
                //判断这个人是不是已完成注册了
                if ($introducer['register_finish'] == 2) {
                    format(CODE_EXIST, '账号已存在');
                }
                $data = array(
                    'name' => $name,
                    'identify_pic_front' => $identifyFront,
                    'identify_pic_back' => $identifyBack,
                    'identify_num' => $identify,
                    'register_finish' => 1
                );
                $result = $introducerModel->save($data, ['id'=>$id, 'status'=>INTRODUCER_OK_STATUS]);
                //$result = $introducerModel->data($data)->where('id', $id)->where('status', INTRODUCER_OK_STATUS)->save();
                if ($result !== false) {
                    format(CODE_OK);
                } else {
                    format(CODE_SYSTEM_FAIL, '系统异常');
                }
            }
        }

    }

    //注册-第三步
    public function registerStep3()
    {
        //Session::set('id', 8);
        $id = intval(Session::get('id'));
        $introducerModel = model('Introducer');
        $introducerData = $introducerModel->where('id', $id)->where('status', INTRODUCER_OK_STATUS)->find();
        if (!empty($introducerData) && !empty($introducerData['name'])
            && !empty($introducerData['identify_pic_front'])
            && !empty($introducerData['identify_pic_back'])
            && !empty($introducerData['identify_num'])
        ) {

            //判断这个人是不是已经走完第二步
            if ($introducerData['register_finish'] < 1) {
                format(CODE_SYSTEM_FAIL, '注册流程出错, 请重新从第一步开始注册');
            }

            $request = Request::instance();
            $bankNum = $request->get('bank_num', '', 'SAFE_REPLACE,REMOVE_XSS');
            $bankCardName = $request->get('bank_card_name', '', 'SAFE_REPLACE,REMOVE_XSS');
            $bank = $request->get('bank_name');
            $bankPic = $request->get('bank_pic', '', 'REMOVE_XSS');

            if (empty($bankNum) || empty($bankCardName) || empty($bank) || empty($bankPic)) {
                format(CODE_PARAM_FAIL, '填入信息有误');
            }

            /*$bankName = getBankName($bankNum);

            if ($bankName === false || $bank != $bankName) {
                format(CODE_PARAM_FAIL, '填入信息有误');
            }*/

            $data = array(
                'bank_card_number' => $bankNum,
                'bank_card_name' => $bankCardName,
                'bank_name' => $bank,
                'bank_pic_front' => $bankPic,
                'register_finish' => 2
            );
            $result = $introducerModel->save($data, ['id'=>$id, 'status'=>INTRODUCER_OK_STATUS]);
            if ($result !== false) {
                $loginToken = makeSkey(Session::get('id') . LOGIN_KEY);
                format(CODE_OK, '', array('sKey' => $loginToken));
            } else {
                format(CODE_SYSTEM_FAIL, '网络错误, 请稍后再试');
            }

        } else {
            format(CODE_SYSTEM_FAIL, '注册流程出错, 请重新从第一步开始注册');
        }

    }

    //个人中心名字
    public function getName()
    {
        //Session::set('id', 8);
        $this->checkLogin();
        $id = Session::get('id');
        $introducerModel = model('Introducer');
        $introducerData = $introducerModel->where('id', $id)->find();
        if (!empty($introducerData['name'])) {
            format(CODE_OK, '', array('name' => $introducerData['name']));
        } else {
            format(CODE_NOT_EXIST, '系统异常');
        }
    }

    //我的客户
    public function customer()
    {
        //Session::set('id', 8);
        $this->checkLogin();
        $request = Request::instance();
        $status = $request->get('status');
        $status = intval($status);
        $id = intval(Session::get('id'));
        switch ($status) {
            case 1:
                $introduce_status = '推介';
                break;
            case 2:
                $introduce_status = '接收';
                break;
            case 3:
                $introduce_status = '认购';
                break;
            case 4:
                $introduce_status = '失效';
                break;
            case 5:
                $introduce_status = '审核通过';
                break;
            default:
                format(CODE_PARAM_FAIL, '非法选项');
        }
        $vipModel = model('Vip');
        $vipData = $vipModel->field('id, name, phone, house, introduce_status, create_time')->where('introducer_id', $id)->where('introduce_status', $introduce_status)->order('update_time desc')->select();
        format(CODE_OK, '', array('list' => $vipData));
    }

    //客户状态
    public function statusLog()
    {
        //Session::set('id', 8);
        $this->checkLogin();
        $request = Request::instance();
        $id = $request->get('vip_id');
        $id = intval($id);
        if ($id > 0) {
            $vipModel = model('Vip');
            $vipInfo = $vipModel->field('introduce_status')->where('id', $id)->find();
            if (empty($vipInfo)) {
                format(CODE_OK, '', array('status' => array()));
            } else {
                $vipStatus = $vipInfo['introduce_status'];
                $introducerModel = model('IntroduceStatusLog');
                $introducerData = $introducerModel->where('introduce_id', $id)->order('create_time desc')->select();
                $status = array();
                $statusMap = array();
                if (!empty($introducerData)) {
                    for ($i = 0; $i < count($introducerData); $i++) {
                        if ($vipStatus == '失效' && $introducerData[$i]['status'] == '审核通过') {
                            continue;
                        } else if ($vipStatus == '审核通过' && $introducerData[$i]['status'] == '失效') {
                            continue;
                        }

                        if ($introducerData[$i]['status'] == '审核通过') {
                            $introducerData[$i]['status'] = '签约';
                        }
                        if (!in_array($introducerData[$i]['status'], $statusMap)) {
                            $status[$introducerData[$i]['status']] = $introducerData[$i]['create_time'];
                            $statusMap[] = $introducerData[$i]['status'];
                        }
                    }
                }
                format(CODE_OK, '', array('status' => $status));
            }
        } else {
            format(CODE_OK, '', array('status' => array()));
        }

    }

    //我的资料
    public function info()
    {
        //Session::set('id', 8);
        $this->checkLogin();
        $id = Session::get('id');
        $idModel = model('Introducer');
        $idData = $idModel->where('id', $id)->find();
        $introduceType = model('IntroducerType')->where('status', 1)->select();
        if (empty($idData)) {
            format(CODE_SYSTEM_FAIL, '系统异常, 稍后再试');
        } else {
            format(CODE_OK, '', array('data' => $idData, 'type' => $introduceType));
        }
    }


    public function editInfo()
    {
        //Session::set('id', 8);
        $this->checkLogin();
        $request = Request::instance();
        $name = $request->get('name', '', 'SAFE_REPLACE,REMOVE_XSS');
        $phone = $request->get('phone');
        $bank = $request->get('bank_name');
        $bankNum = $request->get('bank_num');
        $bankCardName = $request->get('bank_card_name', '', 'SAFE_REPLACE,REMOVE_XSS');
        $type = $request->get('type');
        if (empty($type) || empty($name) || empty($phone) || empty($bank) || empty($bankNum) || empty($bankCardName)) {
            format(CODE_PARAM_FAIL, '填入信息不完整');
        }

        $type = intval($type);
        $isType = model('IntroducerType')->where('id', $type)->where('status', 1)->find();

        if (empty($isType)) {
            format(CODE_PARAM_FAIL, '推荐人属性没有正确选择');
        }

        if (!isPhone($phone)) {
            format(CODE_PARAM_FAIL, '手机号码不正确');
        }

        $data = array();
        /*if (!empty($bank) && !empty($bankNum) && !empty($bankCardName)) {
            $bankName = getBankName($bankNum);

            if ($bankName === false || $bank != $bankName) {
                format(CODE_PARAM_FAIL, '填入信息有误');
            }
            $data['bank_name'] = $bankName;
            $data['bank_card_name'] = $bankCardName;
            $data['bank_card_number'] = $bankNum;
        }*/
        $data['bank_name'] = $bank;
        $data['bank_card_name'] = $bankCardName;
        $data['bank_card_number'] = $bankNum;
        $id = Session::get('id');

        $data['name'] = $name;
        $data['phone'] = $phone;
        $data['introducer_id'] = $type;
        $data['id'] = $id;
        $introducerModel = model('Introducer');
        $introducerModel->save($data, array('id' => $id));
        format(CODE_OK, 'ok', '信息修改成功');

    }
}